package com.city.java.products.service.impl;

import com.city.java.base.utils.PageVO;
import com.city.java.products.mapper.ProductMapper;
import com.city.java.products.pojo.entity.Products;
import com.city.java.base.response.JsonResult;
import com.city.java.base.response.StatusCode;
import com.city.java.products.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商品服务实现类
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public JsonResult addProduct(Products product) {
        log.debug("准备添加商品: {}", product);

        // 参数校验
        if (product == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品信息不能为空");
        }

        if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品名称不能为空");
        }

        if (product.getPointsRequired() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "所需积分不能为空");
        }

        if (product.getPointsRequired() < 0) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "所需积分不能为负数");
        }

        // 设置创建时间
        if (product.getCreatedAt() == null) {
            product.setCreatedAt(LocalDateTime.now());
        }

        // 设置默认库存数量
        if (product.getQuantity() == null) {
            product.setQuantity(0);
        }

        try {
            productMapper.insertProduct(product);
            log.info("商品添加成功: 商品ID={}", product.getProductId());
            return JsonResult.ok();
        } catch (Exception e) {
            log.error("添加商品失败: 商品名称={}", product.getProductName(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "添加商品失败");
        }
    }

    @Override
    public JsonResult getProductById(Long productId) {
        log.debug("根据ID查询商品: {}", productId);

        // 参数校验
        if (productId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品ID不能为空");
        }

        try {
            Products product = productMapper.selectById(productId);
            if (product != null) {
                log.info("查询商品成功: ID={}", productId);
                return JsonResult.ok(product);
            } else {
                log.warn("商品不存在: ID={}", productId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "商品不存在");
            }
        } catch (Exception e) {
            log.error("查询商品失败: ID={}", productId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询商品失败");
        }
    }

    @Override
    public JsonResult getAllProducts() {
        log.debug("查询所有商品列表");

        try {
            List<Products> products = productMapper.selectAll();
            log.info("查询所有商品列表成功: 商品数量={}", products.size());
            return JsonResult.ok(products);
        } catch (Exception e) {
            log.error("查询所有商品列表失败", e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询商品列表失败");
        }
    }

    @Override
    public JsonResult getProductsByPointsRange(Integer minPoints, Integer maxPoints) {
        log.debug("根据积分范围查询商品列表: minPoints={}, maxPoints={}", minPoints, maxPoints);

        try {
            List<Products> products = productMapper.selectByPointsRange(minPoints, maxPoints);
            log.info("查询积分范围商品列表成功: 最小积分={}, 最大积分={}, 商品数量={}", minPoints, maxPoints, products.size());
            return JsonResult.ok(products);
        } catch (Exception e) {
            log.error("查询积分范围商品列表失败: 最小积分={}, 最大积分={}", minPoints, maxPoints, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询商品列表失败");
        }
    }

    @Override
    public JsonResult getProductsByName(String productName) {
        log.debug("根据商品名称查询商品列表: {}", productName);

        // 参数校验
        if (productName == null || productName.trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品名称不能为空");
        }

        try {
            List<Products> products = productMapper.selectByName(productName);
            log.info("查询商品名称列表成功: 商品名称={}, 商品数量={}", productName, products.size());
            return JsonResult.ok(products);
        } catch (Exception e) {
            log.error("查询商品名称列表失败: 商品名称={}", productName, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询商品列表失败");
        }
    }

    @Override
    public JsonResult deleteProductById(Long productId) {
        log.debug("根据ID删除商品: {}", productId);

        // 参数校验
        if (productId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品ID不能为空");
        }

        try {
            int result = productMapper.deleteById(productId);
            if (result > 0) {
                log.info("删除商品成功: ID={}", productId);
                return JsonResult.ok();
            } else {
                log.warn("删除商品失败，商品不存在: ID={}", productId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "商品不存在");
            }
        } catch (Exception e) {
            log.error("删除商品失败: ID={}", productId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "删除商品失败");
        }
    }

    @Override
    public JsonResult updateProduct(Products product) {
        log.debug("更新商品信息: {}", product);

        // 参数校验
        if (product == null || product.getProductId() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "商品ID不能为空");
        }

        if (product.getPointsRequired() != null && product.getPointsRequired() < 0) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "所需积分不能为负数");
        }

        try {
            // 检查商品是否存在
            Products existingProduct = productMapper.selectById(product.getProductId());
            if (existingProduct == null) {
                log.warn("更新商品失败，商品不存在: ID={}", product.getProductId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "商品不存在");
            }

            int result = productMapper.updateById(product);
            if (result > 0) {
                log.info("更新商品成功: ID={}", product.getProductId());
                return JsonResult.ok();
            } else {
                log.warn("更新商品失败: ID={}", product.getProductId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "更新商品失败");
            }
        } catch (Exception e) {
            log.error("更新商品失败: ID={}", product.getProductId(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "更新商品失败");
        }
    }

    @Override
    public PageVO<Products> select(Products products) {
        products.setPageNum(PageVO.build(products.getPageNum(),products.getPageSize()));
        List<Products> list = productMapper.select(products);
        Long totalPage = productMapper.getTotal(products);

        PageVO<Products> pageVO = new PageVO<>();
        pageVO.setList(list);
        pageVO.setTotalPage(totalPage);

        log.debug("查询商品列表成功: {}", pageVO);
        return pageVO;
    }
}
